package com.tongda.menu.adapter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.cuubonandroid.sugaredlistanimations.GPlusListAdapter;
import com.cuubonandroid.sugaredlistanimations.SpeedScrollListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.tongda.core.repository.MenuCartDao;
import com.tongda.core.repository.MenuDishCategoryDAO;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.service.DishService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.DishUtil;
import com.tongda.core.utils.MenuDBHelper;
import com.tongda.core.vo.Dish;
import com.tongda.menu.R;
import com.tongda.menu.R.drawable;
import com.tongda.menu.activity.MainActivity;
import com.tongda.menu.util.ActivityMenuUtil;
import com.tongda.menu.widget.CircleImageView;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class DishAdapter extends GPlusListAdapter{
	private List<Dish> datas;
	private Context context;
	
	  public DishAdapter(Context context, SpeedScrollListener scrollListener,List<Dish> datas) {
		    super(context, scrollListener,datas);
		    this.datas = datas;
		    this.context = context;
		    notifyDataSetChanged();
		  }
	  
    public void startAnimation(View v){
    	AnimationSet animationSet = new AnimationSet(true);
		 TranslateAnimation hideAciton = new TranslateAnimation( 
				 0,100,0,100);
		 hideAciton.setRepeatCount(2);
		 hideAciton.setDuration(500);
		 Animation animation = new ScaleAnimation(1, 0, 1, 0);
		 animation.setDuration(500);
		 animation.setFillAfter(true);
		 
		 animationSet.addAnimation(animation);
		 animationSet.addAnimation(hideAciton);
		
		 animationSet.setFillAfter(true);
    	 v.startAnimation(animationSet);
    }
    
	
	public class Holder{
		private TextView dishnameTv;
		private TextView dishcategoryTv;
		private TextView dishstyleTv;
		private TextView dishsPriceTv;
		private TextView dishpriceTv;
		private Button dishnumberTv;
		private TextView dishorderNumTv;
		
		private ImageView IconzhaopaiImv;
		private ImageView IcontuijianImv;
		private ImageView IcontejiaImv;
		private ImageView IconshijiaImv;
		
	}


	@Override
	protected View getRowView(final int position, View convertView, ViewGroup parent) {
		final Holder holder;
		if(convertView==null){
			holder = new Holder();
			convertView = View.inflate(context, R.layout.adapter_item_dishlist, null);
			holder.dishnameTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishname);
			holder.dishcategoryTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishcategory);
			holder.dishstyleTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishstyle);
			holder.dishsPriceTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishsPrice);
			holder.dishpriceTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishprice);
			holder.dishnumberTv = (Button)convertView.findViewById(R.id.adapter_item_dishlist_dishnumber);
			holder.dishorderNumTv = (TextView)convertView.findViewById(R.id.adapter_item_dishlist_dishordernum);
			holder.IconzhaopaiImv = (ImageView)convertView.findViewById(R.id.main_listitem_icon_zhaopai);
			holder.IcontuijianImv = (ImageView)convertView.findViewById(R.id.main_listitem_icon_tuijian);
			holder.IcontejiaImv = (ImageView)convertView.findViewById(R.id.main_listitem_icon_tejia);
			holder.IconshijiaImv = (ImageView)convertView.findViewById(R.id.main_listitem_icon_shijia);
			
			convertView.setTag(holder);
		}else {
			holder = (Holder) convertView.getTag();
		}
		if(datas.size()==0){
			return convertView;
		}
		final Dish dish = datas.get(position);
		final MenuDishCategoryDAO dishcategory_dao = MenuDishCategoryDAO.getInstance(context);
		final MenuCartDao ordered_dish_dao = MenuCartDao.getInstance(context);
		final MenuDishDao dish_dao = MenuDishDao.getInstance(context);
		final DishUtil dish_util = DishUtil.getInstance(context);
		
		holder.dishnameTv.setText(dish.getDishesName());
		String dishCategoryNameStr = dishcategory_dao.getDishCategoryName(dish.getCategoryId());
		holder.dishcategoryTv.setText(dishCategoryNameStr);
		holder.dishstyleTv.setText(dish.getDishesStyleStr());
		
		holder.dishnumberTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(final View v) {
		       
		       final Handler handler = new Handler(){

				private SQLiteDatabase db = context.openOrCreateDatabase(MenuDBHelper.DATABASE_NAME, Context.MODE_PRIVATE, null);

				@Override
		    	public void handleMessage(Message msg) {
		    		super.handleMessage(msg);
		    		if(((MainActivity)(context)).bound){
		    			((MainActivity)(context)).soundService.playSound();
		    		}
					//如果不在特价时段内，重新定义特价就是原价，插入购物车列表
					if(msg.getData().getString("priceStr").equals("null")){
						dish.setSpecialPrice(dish.getPrice());
					}
					
					if(dish.getIsSet().equals("true")&&dish.getDsDishes()!=null&&dish.getDsDishes().size()>0){
						((MainActivity)context).ordered_dish_dao.insert(dish, ((MainActivity)context).dish_util, ((MainActivity)context).TABLE_NAME,context);
						((MainActivity)context).dish_dao.updateAddNum(dish.getDishesId(), 1);
					}else {
					int orderNum = ordered_dish_dao.getNum(dish.getDishesId());
					if(orderNum==0){
						ordered_dish_dao.insert(dish, dish_util,  ((MainActivity)context).TABLE_NAME,context);
					}else{
						++orderNum;
						ordered_dish_dao.updateNum(dish.getDishesId(), orderNum);
					}
					}
					
					String categoryLevel = dishcategory_dao.getCategoryLevel(context,dish.getCategoryId());
			        String dcIdStr = dish.getCategoryId();
			        if(categoryLevel.equals("2")){
			        	dcIdStr = ((MainActivity)context).dishCategory_dao.getparentCategoryId(dcIdStr);
			        }
			        for(int i=0;i<(((MainActivity)(context)).dishCategoryDatas).size();i++){
			        	if(dcIdStr.equals((((MainActivity)(context)).dishCategoryDatas).get(i).getCategoryId())){
						       int num =  (((MainActivity)(context)).dishCategoryDatas).get(i).getDishNum();
						       num++;
						       (((MainActivity)(context)).dishCategoryDatas).get(i).setDishNum(num);
			        		break;
			        	}
			        }
			        /*
			         * 处理菜肴的已点份数
			         * */
			        int dishorderNum =  dish.getDishorderNum();
			       dishorderNum++;
			       dish.setDishorderNum(dishorderNum);
					((MainActivity)(context)).dishAdapter.notifyDataSetChanged();
			       dish_dao.updateNum(dish.getDishesId(), dishorderNum);
			       
			       if(categoryLevel.equals("2")){
			    	   ((MainActivity)(context)).subCategoryId = dish.getCategoryId();
			       }
			       
			       if(!((MainActivity)(context)).subCategoryId.equals("")){
			    	   ((MainActivity)(context)).updatedcDishNum(((MainActivity)(context)).subCategoryId,db );
			    	   if(((MainActivity)(context)).flag){
			    		   ((MainActivity)(context)).updatesubCategory();
			    	   }
			       }
			       
					int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
					v.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
					CircleImageView buyImg = new CircleImageView(context);
			    	buyImg.setBackgroundResource(R.drawable.scroll);
					((MainActivity)context).setAnim(buyImg, start_location,1);// 开始执行动画
					
		    	}  
		       };
		       Thread judgePriceThread = new Thread(new Runnable() {
		    		private String priceStr = "";
				@Override
				public void run() {
					Message msg = handler.obtainMessage();
					if(dish.getSpecialPrice()!=null && ActivityMenuUtil.checkNetworkState(context)){
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
						String creatTimeStr = format.format(new Date());
						BigDecimal price = DishService.judgePrice(dish.getDishesId(), dish.getIsSet(),creatTimeStr);
						priceStr  = price+"";
					}
						Bundle bundle = new Bundle();
						bundle.putString("priceStr", priceStr);
						msg.setData(bundle );
						handler.sendMessage(msg);
				}
			});
		       
				if(!((MainActivity)context).btnisClicked){
					judgePriceThread.start();
				}else{
					ActivityUtil.Toast(((MainActivity)context), "请等待处理完成", false, false);
				}
				
			}
		});
		
        /*
         * 处理价格
         * */
		if(dish.getIsRulingPrice()!=null && dish.getIsRulingPrice().equals("1")){
        	holder.dishsPriceTv.setVisibility(View.GONE);
        	holder.dishpriceTv.setText("￥"+dish.getRulingPrice()+"/"+dish.getUnitName());
        	holder.dishpriceTv.getPaint().setFlags(0);
		}else{
        if(dish.getSpecialPrice()!=null){
        	holder.dishsPriceTv.setVisibility(View.VISIBLE);
        	holder.dishsPriceTv.setText(Html.fromHtml("<font color='#ffffff' type='bold'>"+"￥"+dish.getSpecialPrice()+"/"+dish.getUnitName()+"</font>"));
        	holder.dishpriceTv.setText("￥"+dish.getPrice());
        	holder.dishpriceTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        }else{
        	holder.dishsPriceTv.setVisibility(View.GONE);
        	holder.dishpriceTv.setText("￥"+dish.getPrice()+"/"+dish.getUnitName());
        	holder.dishpriceTv.getPaint().setFlags(0);
        }
		}
        holder.dishnameTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((MainActivity)(context)).dishCurrentPosition = position;
				if(((MainActivity)(context)).dishCategory_util.init4DishesCategory().size()>0){
				if(((MainActivity)(context)).flag){
					((MainActivity)(context)).showMenuShowActivity(dish.getCategoryId(), position);
				}else{
					if(!((MainActivity)(context)).isClicked){
						((MainActivity)(context)).dishCategoryId = "all";
					}
					((MainActivity)(context)).showMenuShowActivity(((MainActivity)(context)).dishCategoryId, position);
				}
				}else{
					((MainActivity)(context)).showMenuShowActivity(((MainActivity)(context)).dishCategoryId, position);
				}
			}
		});
        
        if(dish.getDishorderNum()>0){
        	 Typeface typeFace =Typeface.createFromAsset(context.getAssets(),"hwcy.ttf");
        	 holder.dishorderNumTv.setTypeface(typeFace);
        	 holder.dishorderNumTv.setText("x "+dish.getDishorderNum()+"");
        }else{
        	 holder.dishorderNumTv.setText("");
        }
       
        
        /*
         * 处理估清菜肴
         * */
        if(dish.getEstimate()!=null &&dish.getEstimate()<=0f){
        	holder.dishnumberTv.setEnabled(false);
        	holder.dishnumberTv.setText("已售完");
        	holder.dishnameTv.setTextColor(Color.GRAY);
        	holder.dishcategoryTv.setTextColor(Color.GRAY);
        	holder.dishstyleTv.setTextColor(Color.GRAY);
        	holder.dishpriceTv.setTextColor(Color.GRAY);
        }else{
        	holder.dishnumberTv.setEnabled(true);
        	holder.dishnumberTv.setText("来一份");
        	holder.dishnameTv.setTextColor(context.getResources().getColor(R.color.white));
        	holder.dishcategoryTv.setTextColor(context.getResources().getColor(R.color.white));
        	holder.dishstyleTv.setTextColor(context.getResources().getColor(R.color.white));
        	holder.dishpriceTv.setTextColor(context.getResources().getColor(R.color.white));
        }
        
        
        /*
         * 处理图标
         * */
        if(!dish.getIsSpecialty().equals("null")){
        	holder.IconzhaopaiImv .setVisibility(View.VISIBLE);
        	holder.IconzhaopaiImv .setBackgroundResource(drawable.zhaopai_small);
        }else{
        	holder.IconzhaopaiImv .setVisibility(View.GONE);
        }
        
        if(!dish.getIsRecommend().equals("null")){
        	holder.IcontuijianImv .setVisibility(View.VISIBLE);
        	holder.IcontuijianImv .setBackgroundResource(drawable.tuijian_small);
        }else{
        	holder.IcontuijianImv .setVisibility(View.GONE);
        }
        
        if(dish.getSpecialPrice()!=null || dish.getMemberPrice()!=null){
        	holder.IcontejiaImv .setVisibility(View.VISIBLE);
        	holder.IcontejiaImv .setBackgroundResource(drawable.tejia_small);
        }else{
        	holder.IcontejiaImv .setVisibility(View.GONE);
        }
        
        if(dish.getIsRulingPrice()!=null &&dish.getIsRulingPrice().equals("1")){
        	holder.IconshijiaImv .setVisibility(View.VISIBLE);
        	holder.IconshijiaImv .setBackgroundResource(drawable.shijia_small);
        }else{
        	holder.IconshijiaImv .setVisibility(View.GONE);
        }
        
		return convertView;
	}

	public List<Dish> getDatas() {
		return datas;
	}

	public void setDatas(List<Dish> datas) {
		this.datas = datas;
		notifyDataSetChanged();
	}
	
}
